const express = require("express");
const fs = require("fs");
const multer = require("multer");
// 一个解析文件上传的插件
// 提供文件上传的对象
const upload = multer({});
// const upload = multer({dest:'./img'})
const router = express.Router();
// upload.single("imgFile") 单文件上传 key 为 imgFile

router.post("/upload", upload.single("imgFile"), async (req, res) => {
  // req.file 包含文件上传信息
  // console.log(req.file);
  const { mimetype, buffer, size } = req.file;
  // 通过size 进行尺寸验证
  if (size >= 1000 * 1024) {
    return res.send({ code: -1, msg: "超过最大限制" });
  }
  // 通过mimetype 做类型验证
  const type = mimetype.split("/")[1];
  const limitArr = ["png", "jpg", "jpeg"];
  if (!limitArr.includes(type)) {
    return res.send({ code: -2, msg: "文件类型错误" });
  }
  // 将文件上传信息写入到服务器
  const fileName = new Date().getTime() + Math.random() * 99999 + "." + type;
  const path = `http://192.168.52.140:3000/imgFiles/${fileName}`;
  fs.writeFileSync(`./img/${fileName}`, buffer);
  res.send({ msg: "图片上传成功", code: 0, path });
});

module.exports = router;
